package org.budo.redis.jdbc.driver.statement.set;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.budo.jdbc.driver.AbstractBudoJdbcPreparedStatement;
import org.budo.jdbc.driver.resultset.impl.ObjectArrayResultSet;
import org.budo.redis.jdbc.driver.BudoRedisJdbcConnection;
import org.budo.redis.jdbc.driver.executor.RedisStatementExecutor;
import org.budo.redis.jdbc.driver.parser.RedisSqlStatement;
import org.budo.redis.jdbc.driver.statement.AbstractRedisStatement;

/**
 * @author lmw
 */
public class SRANDMEMBER extends AbstractRedisStatement {
    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException{
        byte[] key = this.parameter(0, preparedStatement);

        Integer count;
        if (((RedisSqlStatement) this.getSqlStatement()).getFunctionParameters().length < 2) {
            count = null;
        } else {
            count = this.parameterNumber(1, preparedStatement).intValue();
        }

        RedisStatementExecutor statementExecutor = ((BudoRedisJdbcConnection) preparedStatement.getConnection()).getStatementExecutor();
        byte[][] srandmember = statementExecutor.srandmember(key, count);

        ResultSet resultSet = new ObjectArrayResultSet(new String[] { "srandmember" }, srandmember);
        ((AbstractBudoJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
    }
}